<template>
    
       <el-main>
          <!-- 查询条件 -->
          <el-form ref="searchForm" label-width="80px" :inline="true" size="small">
          <el-form-item>
            <el-input v-model="searchModel.name" placeholder="请输入分区名字"/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="search()">查询</el-button>
            <el-button icon="el-icon-refresh-right" @click="clearSearchModel()">重置</el-button>
            <el-button type="success" icon="el-icon-plus"   @click="assignCity()" v-if="hasPermission('resource:weather:add')">新增</el-button>
          </el-form-item>
        </el-form>

            <el-row :gutter="12"  type="flex" justify="left">

                <el-col :span="4" v-for="(item,index) in plateList" :key="index" >
                    <el-card shadow="always" style="text-align: center;" >
                        <el-progress type="dashboard" :percentage="item.total" :color="colors"></el-progress>
                        <div>
                          <el-tag :type="tagType[Math.floor(item.total/20)]" v-text="item.name" @click="openAddWindow(item)"></el-tag>
                        </div>
                    </el-card>
                </el-col>
 
            </el-row>

           <!-- 添加修改窗口 -->
     <system-dialog
      :title="pictureDialog.title"
      :visible="pictureDialog.visible"
      :width="pictureDialog.width"
      :height="pictureDialog.height"
      @onClose="onClose()"
      @onConfirm="onConfirm()"
    >
      <div slot="content">
        <el-form
          :model="pictureObject"
          ref="pictureForm"
          label-width="120px"
          :inline="true"
          size="small">

   
            <el-form-item label="图片名字" prop="name">
              <el-input v-model="pictureObject.name" placeholder="填充图片名字" ></el-input>
            </el-form-item>

            
            <el-form-item label="创建者" prop="creatorId">
              <el-input v-model="pictureObject.creatorId" readonly></el-input>
            </el-form-item>

            <el-form-item label="描述" prop="description">
              <el-input v-model="pictureObject.description" placeholder="填充描述" ></el-input>
            </el-form-item>
            <!-- popper-class="date-class" 
              :append-to-body="false" -->
            <el-form-item 
              label="图片标签" 
              prop="tags"  
              class="add_advice"
              id="adviceTag">
              <el-select 
                ref = "optionRef"
                v-model="tagList.id" 
                multiple 
                clearable
                filterable
                allow-create
                default-first-option
                @change="changeTagColor($event)"
                placeholder="请选择">
                <el-option
                  v-for="item in tagList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                  >
                </el-option>
              </el-select>
            </el-form-item>

            <!-- 图片 -->
            <el-form-item label="图片">

              <el-upload
              class="upload-demo"
              ref="upload"
              :action="uploadURL+'/api/picture/manager/upload?plateName='+plateName"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleImageSuccess"
              :before-upload="beforeImageUpload"
              :file-list="fileList"
              accept="image/*"
              :data="uploadHeader"
              :auto-upload="false">
              <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
              <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
              <div slot="tip" class="el-upload__tip">只能上传图片文件</div>
            </el-upload>
             

            </el-form-item>

        </el-form>
      </div>
    </system-dialog>
       </el-main>
</template>

<script>
//导入plate.js脚本
import plateApi from '@/api/picture/plate';
import SystemDialog from '@/components/system/Systemdialog'
//导入token
import {getToken} from '@/utils/auth'
//导入tag.js脚本
import tagApi from '@/api/picture/tag';

import pictureApi from '@/api/picture/picture';

const IS_PROD = process.env.NODE_ENV === 'production'; //是否是生产模式
const preUrl = IS_PROD ? 'http://47.114.73.72:5577' : 'http://localhost:5577'; //是生产模式 '' ，不是则 '/api'

export default {
  name: "picture-upload",
  components:{
      SystemDialog
    },
    data() {
      return {
        uploadURL: preUrl ,
        fileList:[],
        fileObject:[],
        plateList : [] ,
        tagType:['','success','warning','danger','info'],
        searchModel :{
            name: '',  //分区名字
        },
        dialogImageUrl: '',
        dialogVisible: false,
        disabled: false,
        tagColorList: [
            '#FF6666',
            '#FF9951',
            '#80C459',
            '#59A56E',
            '#65ADD4',
            '#3D65A1',
            '#372E7C',
            '#5F216D',
            '#903FBF',
            '#BF2F7E'
        ],
        colors: [
          {color: '#FF0000', percentage: 100},
          {color: '#FF006C', percentage: 95},
          {color: '#FF6E76', percentage: 90},
          {color: '#FFD000', percentage: 85},
          {color: '#FFF600', percentage: 80}, 
          {color: '#FF00A9', percentage: 75},
          {color: '#FF00D7', percentage: 70},
          {color: '#E900FF', percentage: 65},
          {color: '#CA00FF', percentage: 60},
          {color: '#8500FF', percentage: 55},
          {color: '#4000FF', percentage: 50},
          {color: '#000DFF', percentage: 45},
          {color: '#005AFF', percentage: 40},
          {color: '#00A7FF', percentage: 35},
          {color: '#00ECFF', percentage: 30},
          {color: '#00FFCD', percentage: 25},
          {color: '#00FF71', percentage: 20},
          {color: '#57FF00', percentage: 15},
          {color: '#95FF00', percentage: 10},
          {color: '#D2FF00', percentage: 5},
        ],
        tagList: [], //标签选向
        value: '',
        plateName: '' , //分区名字
        //上传需要携带的数据
      uploadHeader:{  
         "Authorization" : getToken() 
      },

      pictureDialog: {
          title: "",      //窗口标题
          visible: false, //是否显示窗口
          width: 700,      //窗口宽度
          height: 300,    //窗口高度们
      },
      pictureObject:{
        id: '', 
        plateId: '',
        name: '',
        url: '',
        tags: '',
        description: '',
        creatorId: this.$store.getters.userId, //会被清除
      },
      plateName : '' , //分区名字
     
    }
  },
    methods: {

      submitUpload() {
        this.$refs.upload.submit();
      },
      handleRemove(file, fileList) {
        let uid = file.uid ;
        for(let i = 0 ; i < this.fileObject.length ; i++){
             if(this.fileObject[i].uid === uid){
               this.fileObject.splice(i, 1);
             } 
        }
        console.log(this.fileObject)
     
      },
      handlePreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      handleImageSuccess(res, file) {
           this.fileObject.push({'uid':file.uid,'url':res.data})
           console.log(this.fileObject)
      },
      beforeImageUpload(file) {
          const isLt100M = file.size / 1024 / 1024 < 100
          if (!isLt100M) {
              this.$message.error('上传头像图片大小不能超过 100MB!')
          }
          return isLt100M
       },

      changeTagColor(event) {
          let tagdom = document.getElementsByClassName('el-tag--info')
          tagdom.forEach(item => {
          let a = Math.floor(Math.random() * this.colors.length);
            item.style.setProperty('--tagColor',  this.colors[a].color)
          })
      },

      async showPlates(){
         let response = await plateApi.getPlateList();
         this.plateList = response.data;
      },
        /**
          * 打开添加窗口
          */
         async openAddWindow(item) {   
    
              this.$resetForm("pictureForm",this.pictureObject);  //清空表单数据 
              this.fileList = [] ;
              this.pictureObject.creatorId = this.$store.getters.userId //当前登录用户id
              let res = await tagApi.getAllTagApi()
              if(res.success){
                 this.tagList = res.data;
                 this.pictureDialog.title = "【"+item.name +"】"//设置窗口标题
                 this.pictureDialog.visible = true//显示窗口
                 this.pictureObject.plateId = item.id
                 this.plateName = item.name
              }else{
                this.$message.error('加载标签失败');
              }
             

          },
          /**
          * 窗口取消事件
          */
          onClose() {
              this.pictureDialog.visible = false
          },
          /**
          * 窗口确认事件
          */
          onConfirm() {
            
              //表单验证
              this.$refs.pictureForm.validate(async (valid)=>{
              if(valid){
                  //设置tags
                  let options = this.$refs.optionRef.selected
                  this.pictureObject.tags = '';
                  for(let index in options){
                      this.pictureObject.tags += options[index].value + ",";
                  }
                  //设置urls
                  if(this.fileObject.length === 0){
                    this.$message.error("请至少上传一张图片");
                    return;
                   }
                  let res = null;
                  this.pictureObject.url = '';
                  for(let index in this.fileObject){
                      let obj  = this.fileObject[index];
                      if(obj.url != "" && obj.url != undefined){
                         this.pictureObject.url += obj.url +',';
                      }
                  }
                  //判断角色ID是否为空
                  if (this.pictureObject.id === "") {
                      //新增
                      //发送添加请求
                       res = await pictureApi.addPictureApi(this.pictureObject);
                  } else {
                      //发送修改请求
                      res = await pictureApi.updatePictureApi(this.pictureObject);
                  }
                  //判断是否成功
                  if (res.success) {
                      this.$message.success(res.message);
                      //刷新
                      this.showPlates();
                      //关闭窗口
                      this.pictureDialog.visible = false;
                      //清空
                      this.fileObject = [];
                  } else {
                      this.$message.error(res.message);
                  }
              }
              });

          },
       
  

    },
    created(){
      console.log("aaaaa:"+this.uploadURL)
      this.showPlates();
   
    },
    computed: {
      
    },
  }
</script>

<style lang="scss" scoped>
.add_advice {
    .el-tag,
    .el-tag.el-tag--info {
      // 获取--tagColor的值
      background-color: var(--tagColor);
      border-color: var(--tagColor);
      color: black ;
    }
  }

</style>